﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Net;

namespace ACPLogAnalyzer
{
    public class AppVersionChecker
    {
        #region Members
        public event EventHandler<DownloadProgressChangedEventArgs> DownloadProgress;
        public event EventHandler DownloadComplete;

        private bool m_isUpdateAvailable;
        public bool IsUpdateAvailable
        {
            get { return m_isUpdateAvailable; }
            set { m_isUpdateAvailable = value; }
        }

        private bool m_updateDownloaded;
        public bool UpdateDownloaded
        {
            get { return m_updateDownloaded; }
            set { m_updateDownloaded = value; }
        }

        private double m_runningVersion;
        public double RunningVersion
        {
            get { return m_runningVersion; }
            set { m_runningVersion = value; }
        }

        private double m_availableVersion;
        public double AvailableVersion
        {
            get { return m_availableVersion; }
            set { m_availableVersion = value; }
        }
        #endregion

        public AppVersionChecker()
        {
            m_isUpdateAvailable = false;
            m_updateDownloaded = false;
            m_runningVersion = 0;
            m_availableVersion = 0;
        }

        public bool CheckForUpdate()
        {
            try
            {
                WebRequest request;
                WebResponse response;
                Stream stream;
                StreamReader sr;
                string version;

                // We expect a string like: "CurrentVersion=n.nn" (where n = 0..9)
                request = WebRequest.Create(Properties.Settings.Default.Version_Check_Url);
                response = request.GetResponse();
                stream = response.GetResponseStream();
                sr = new StreamReader(stream);
                string verInfo = sr.ReadToEnd();
                if (string.IsNullOrEmpty(verInfo))
                {
                    IsUpdateAvailable = false;
                    return false;
                }

                version = verInfo.Substring(verInfo.IndexOf("=") + 1);

                // This version is available from the web:
                m_availableVersion = double.Parse(version);

                // What's the running app's version?
                version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() +
                "." +
                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString() +
                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Build.ToString();

                m_runningVersion = double.Parse(version);

                // Compare versions...
                IsUpdateAvailable = false;
                if (m_availableVersion > m_runningVersion)  // Newer version available
                    IsUpdateAvailable = true;
            }
            catch
            {
            }

            return IsUpdateAvailable;
        }

        public void StartUpdateDownload()
        {
            try
            {
                UpdateDownloaded = false;

                // Save the installer to the Windows\Temp directory...
                string path = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\Temp\" +
                    System.IO.Path.GetFileName(Properties.Settings.Default.Update_Download_Url);

                using (WebClient webClient = new WebClient())
                { 
                    webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(DownloadFileCompleted);
                    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
                    webClient.DownloadFileAsync(new Uri(Properties.Settings.Default.Update_Download_Url), path);
                }
            }
            catch
            {
            }
        }

        private void DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            // Bubble up the event for the Update window that created us
            if (DownloadComplete != null)
                DownloadComplete(this, System.EventArgs.Empty);

            UpdateDownloaded = true;
        }

        private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            // Bubble up the event for the Update window that created us
            if(DownloadProgress != null)
                DownloadProgress(this, e);
        }

        public void RemoveInstaller()
        {
            try
            {
                string path = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\Temp\" +
                    System.IO.Path.GetFileName(Properties.Settings.Default.Update_Download_Url);

                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
            }
            catch
            {
                // Fail silently 
            }
        }
    }
}
